package com.zgxl.common.query;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * @author pumbaa
 * @since 1.0
 */
public class DateTimeQuery {
    private static Formatter formatter;

    public DateTimeQuery() {
        if (null == formatter) {
            formatter = new Formatter();
        }
    }

    /**
     * 起始日期字符串,格式:yyyy-MM-dd
     */
    private String startDate;
    /**
     * 结束日期字符串,格式: yyyy-MM-dd
     */
    private String endDate;
    /**
     * 起始时间戳,单位:秒
     */
    private Long startTime;
    /**
     * 结束时间戳,单位:秒
     */
    private Long endTime;

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public Long getStartTime() {
        return startTime;
    }

    public void setStartTime(Long startTime) {
        this.startTime = startTime;
    }

    public Long getEndTime() {
        return endTime;
    }

    public void setEndTime(Long endTime) {
        this.endTime = endTime;
    }

    public void format(){
        startTime = formatter.getDateStartTime(startDate);
        endTime = formatter.getDateEndTime(endDate);
    }

    private class Formatter {
        private SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        long getDateStartTime(String dateStr) {
            if (isEmpty(dateStr)) {
                return 0;
            }
            try {
                return dateFormat.parse(dateStr).getTime() / 1000;
            } catch (ParseException e) {
                return 0;
            }
        }

        long getDateEndTime(String dateStr) {
            if (isEmpty(dateStr)) {
                return 0;
            }
            try {
                dateStr = dateFormat.format(dateFormat.parse(dateStr));
                dateStr += " 23:59:59";
                return timeFormat.parse(dateStr).getTime() / 1000;
            } catch (ParseException e) {
                return 0;
            }
        }

        private boolean isEmpty(String str) {
            return null == str || str.length() == 0;
        }
    }
}
